#include "../include/head.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>

// 全局订单链表
ListNode *order_list = NULL;

// 订单比较函数（按ID）
int compare_order_by_id(void *a, void *b) {
    Order *order_a = (Order*)a;
    char *id_b = (char*)b;
    return strcmp(order_a->order_id, id_b) == 0 ? 0 : 1;
}

// 订单比较函数（按用户ID）
int compare_order_by_user_id(void *a, void *b) {
    Order *order_a = (Order*)a;
    int *user_id_b = (int*)b;
    return order_a->user_id == *user_id_b ? 0 : 1;
}

// 从文件加载所有订单到链表
void load_all_orders() {
    FILE *file = fopen("./supermarket_management/data/orders.txt", "r");
    if (file) {
        Order *order;
        while (1) {
            order = (Order*)malloc(sizeof(Order));
            if (fscanf(file, "%49[^,],%d,%19[^,],%d,%lf,%49[^,],%d\n",
                    order->order_id,
                    &order->user_id,
                    order->goods_id,
                    &order->quantity,
                    &order->total_amount,
                    order->order_time,
                    &order->order_status) != 7) {
                free(order);
                break;
            }
            insert_at_end(&order_list, order);
        }
        fclose(file);
        printf("已加载 %d 个订单到内存\n", get_list_length(order_list));
    } else {
        printf("订单文件不存在，将创建新的订单数据\n");
    }
}

// 保存所有订单到文件
void save_all_orders() {
    FILE *file = fopen("./supermarket_management/data/orders.txt", "w");
    if (file) {
        ListNode *current = order_list;
        while (current != NULL) {
            Order *order = (Order*)current->data;
            fprintf(file, "%s,%d,%s,%d,%.2f,%s,%d\n",
                    order->order_id,
                    order->user_id,
                    order->goods_id,
                    order->quantity,
                    order->total_amount,
                    order->order_time,
                    order->order_status);
            current = current->next;
        }
        fclose(file);
        printf("所有订单数据已保存\n");
    } else {
        printf("保存订单数据失败\n");
    }
}

// 生成订单ID
void generate_order_id(char *order_id) {
    time_t now = time(NULL);
    struct tm *t = localtime(&now);
    sprintf(order_id, "ORD%d%02d%02d%02d%02d%02d%d",
            t->tm_year + 1900,
            t->tm_mon + 1,
            t->tm_mday,
            t->tm_hour,
            t->tm_min,
            t->tm_sec,
            rand() % 1000);
}

// 获取当前时间字符串
void get_current_time(char *time_str) {
    time_t now = time(NULL);
    struct tm *t = localtime(&now);
    sprintf(time_str, "%d-%02d-%02d %02d:%02d:%02d",
            t->tm_year + 1900,
            t->tm_mon + 1,
            t->tm_mday,
            t->tm_hour,
            t->tm_min,
            t->tm_sec);
}

// 初始化订单系统
void init_order_system() {
    srand(time(NULL)); // 初始化随机数种子
    load_all_orders();
}

// 创建订单
Order* create_order(int user_id, char *goods_id, int quantity) {
    // 检查用户是否存在
    User *user = find_user_by_id(user_id);
    if (user == NULL) {
        printf("用户不存在！\n");
        return NULL;
    }
    
    // 检查商品是否存在
    Goods *goods = find_goods_by_id(goods_id);
    if (goods == NULL) {
        printf("商品不存在！\n");
        return NULL;
    }
    
    // 检查库存是否足够
    if (goods->stock < quantity) {
        printf("库存不足！当前库存：%d\n", goods->stock);
        return NULL;
    }
    
    // 创建新订单
    Order *new_order = (Order*)malloc(sizeof(Order));
    if (new_order == NULL) {
        printf("内存分配失败\n");
        return NULL;
    }
    
    // 设置订单信息
    generate_order_id(new_order->order_id);
    new_order->user_id = user_id;
    strcpy(new_order->goods_id, goods_id);
    new_order->quantity = quantity;
    
    // 计算订单金额（考虑特价）
    double price = goods->price;
    if (goods->is_special) {
        price *= 0.8; // 特价商品8折
    }
    new_order->total_amount = price * quantity;
    
    // 设置订单时间和状态
    get_current_time(new_order->order_time);
    new_order->order_status = 0; // 未支付
    
    // 添加到订单链表
    insert_at_end(&order_list, new_order);
    
    // 保存订单数据
    save_all_orders();
    
    printf("订单创建成功！订单ID：%s\n", new_order->order_id);
    show_order(new_order);
    
    return new_order;
}

// 显示订单信息
void show_order(Order *order) {
    if (order == NULL) {
        printf("错误：订单信息为空\n");
        return;
    }
    
    // 获取用户和商品信息用于显示
    User *user = find_user_by_id(order->user_id);
    Goods *goods = find_goods_by_id(order->goods_id);
    
    printf("\n========== 订单信息 ==========\n");
    printf("订单ID: %s\n", order->order_id);
    printf("用户ID: %d\n", order->user_id);
    if (user != NULL) {
        printf("用户名: %s\n", user->username);
    }
    printf("商品ID: %s\n", order->goods_id);
    if (goods != NULL) {
        printf("商品名称: %s\n", goods->name);
        printf("商品单价: %.2f元\n", goods->price);
    }
    printf("购买数量: %d\n", order->quantity);
    printf("订单金额: %.2f元\n", order->total_amount);
    printf("下单时间: %s\n", order->order_time);
    
    // 显示订单状态
    char *status_str;
    switch (order->order_status) {
        case 0: status_str = "未支付"; break;
        case 1: status_str = "已支付"; break;
        case 2: status_str = "已取消"; break;
        default: status_str = "未知状态"; break;
    }
    printf("订单状态: %s\n", status_str);
    printf("==============================\n");
}

// 按ID查找订单
Order* find_order_by_id(char *order_id) {
    ListNode *found = find_node(order_list, order_id, compare_order_by_id);
    return found ? (Order*)found->data : NULL;
}

// 显示用户的所有订单
void show_user_orders(int user_id) {
    printf("\n========== 用户订单列表 ==========\n");
    printf("%-20s %-10s %-20s %-10s %-10s %-15s %-10s\n", 
           "订单ID", "商品ID", "商品名称", "数量", "金额", "下单时间", "状态");
    printf("-------------------------------------------------------------------------------------------------------\n");
    
    int count = 0;
    ListNode *current = order_list;
    while (current != NULL) {
        Order *order = (Order*)current->data;
        if (order->user_id == user_id) {
            Goods *goods = find_goods_by_id(order->goods_id);
            char status_str[20];
            switch (order->order_status) {
                case 0: strcpy(status_str, "未支付"); break;
                case 1: strcpy(status_str, "已支付"); break;
                case 2: strcpy(status_str, "已取消"); break;
                default: strcpy(status_str, "未知状态"); break;
            }
            
            printf("%-20s %-10s %-20s %-10d %-10.2f %-15s %-10s\n",
                   order->order_id,
                   order->goods_id,
                   goods ? goods->name : "未知",
                   order->quantity,
                   order->total_amount,
                   order->order_time,
                   status_str);
            count++;
        }
        current = current->next;
    }
    
    if (count == 0) {
        printf("暂无订单记录！\n");
    }
    printf("=======================================================================================================\n");
}

// 取消订单
int cancel_order(char *order_id) {
    Order *order = find_order_by_id(order_id);
    if (order == NULL) {
        printf("订单不存在！\n");
        return -1;
    }
    
    if (order->order_status != 0) {
        printf("只能取消未支付的订单！\n");
        return -1;
    }
    
    order->order_status = 2; // 已取消
    save_all_orders();
    printf("订单已取消！\n");
    return 0;
}

// 支付订单
int pay_order(char *order_id) {
    Order *order = find_order_by_id(order_id);
    if (order == NULL) {
        printf("订单不存在！\n");
        return -1;
    }
    
    if (order->order_status != 0) {
        printf("只能支付未支付的订单！\n");
        return -1;
    }
    
    // 获取用户信息
    User *user = find_user_by_id(order->user_id);
    if (user == NULL) {
        printf("用户不存在！\n");
        return -1;
    }
    
    // 检查余额是否足够
    if (user->balance < order->total_amount) {
        printf("账户余额不足！当前余额：%.2f元，需要：%.2f元\n", user->balance, order->total_amount);
        return -1;
    }
    
    // 扣除余额
    user->balance -= order->total_amount;
    
    // 增加积分（消费1元获得1积分）
    user->points += order->total_amount;
    
    // 更新商品库存
    Goods *goods = find_goods_by_id(order->goods_id);
    if (goods != NULL) {
        goods->stock -= order->quantity;
        save_all_goods(); // 保存商品数据
    }
    
    // 更新订单状态
    order->order_status = 1; // 已支付
    
    // 保存数据
    save_all_users_to_file();
    save_all_orders();
    
    printf("订单支付成功！\n");
    printf("扣除余额：%.2f元，当前余额：%.2f元\n", order->total_amount, user->balance);
    printf("获得积分：%.2f分，当前积分：%.2f分\n", order->total_amount, user->points);
    
    return 0;
}

// 显示所有订单
void show_all_orders() {
    printf("\n========== 所有订单列表 ==========\n");
    printf("%-20s %-10s %-15s %-10s %-20s %-10s %-10s %-15s %-10s\n", 
           "订单ID", "用户ID", "用户名", "商品ID", "商品名称", "数量", "金额", "下单时间", "状态");
    printf("-----------------------------------------------------------------------------------------------------------------------------------------------------\n");
    
    ListNode *current = order_list;
    while (current != NULL) {
        Order *order = (Order*)current->data;
        User *user = find_user_by_id(order->user_id);
        Goods *goods = find_goods_by_id(order->goods_id);
        char status_str[20];
        switch (order->order_status) {
            case 0: strcpy(status_str, "未支付"); break;
            case 1: strcpy(status_str, "已支付"); break;
            case 2: strcpy(status_str, "已取消"); break;
            default: strcpy(status_str, "未知状态"); break;
        }
        
        printf("%-20s %-10d %-15s %-10s %-20s %-10d %-10.2f %-15s %-10s\n",
               order->order_id,
               order->user_id,
               user ? user->username : "未知",
               order->goods_id,
               goods ? goods->name : "未知",
               order->quantity,
               order->total_amount,
               order->order_time,
               status_str);
        current = current->next;
    }
    printf("=====================================================================================================================================================\n");
}